import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

import { Subject } from 'rxjs/Subject';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { ReplaySubject } from 'rxjs/ReplaySubject';
import 'rxjs/observable/fromEvent';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/pluck';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/debounceTime';

import * as R from 'ramda';

import { getMarkdown } from '../markdown/index';
import { request } from './request';

@Component({
  selector: 'app-editor',
  templateUrl: './editor.component.html',
  styleUrls: ['./editor.component.scss']
})
export class EditorComponent implements OnInit {

  markdown: any;
  content$: Subject<string> = new ReplaySubject<string>();
  rendered$: Subject<string> = new ReplaySubject<string>();

  file: any = {};

  constructor(
    private route: ActivatedRoute,
  ) {
      this.route.params
        .pluck('fileId')
        .subscribe(async (fileId) => {
          const req = await request(`http://127.0.0.1:3000/file/${fileId}`);
          this.file = req[0];
          this.content$.next(this.file.fileCnt || '');
        });
    this.markdown = getMarkdown();
  }

  ngOnInit() {
    this.content$.next('# markdown-it rulezz!');
    this.content$
      .distinctUntilChanged()
      .debounceTime(1000)
      .map((value) => this.markdown.render(value))
      .distinctUntilChanged()
      .subscribe(this.rendered$);
    this.content$.subscribe((content) => this.file.fileCnt = content);
  }

  handle($event) {
    const content = $event.target.value;
    this.content$.next(content);
  }

  async store() {
    const { fileID } = this.file;
    console.log(this.file);
    const req = await request(`http://127.0.0.1:3000/file/${fileID}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(this.file),
    });
    console.log(req);
  }

  back() {
    location.replace(`/${this.file.filePath}`);
  }

}
